package rensoft.android;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.Thread.UncaughtExceptionHandler;

import static rensoft.java.lang.Lang.error;

import android.os.Environment;
import rensoft.android.lang.IAplication;
import rensoft.java.lang.Base;

public abstract class ApplicationBase extends Base implements IAplication, UncaughtExceptionHandler {

  public ApplicationBase() {
    Thread.currentThread().setUncaughtExceptionHandler(this);
  }

  public void uncaughtException(Thread thread, final Throwable ex) {
    error(ex);
    ex.printStackTrace();
    writeExceptionToSdlogFile(ex);
  }

  private void writeExceptionToSdlogFile(Throwable ex) {
    String logpath =
        Environment.getExternalStorageDirectory() + "/" + getApplicationName() + ".log";
    PrintWriter writer;
    try {
      writer = new PrintWriter(new FileWriter(logpath, true));
      ex.printStackTrace(writer);
      writer.flush();
      writer.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
